<template>
    <div
        v-if="attr.id !== 'canvas'"
        :key="render_trigger"
    >
        <v-row no-gutters>
            <v-col
                cols="3"
                class="d-flex justify-start"
            >
                <h4 style="margin: 10px 0 10px 5px">DEFAULT</h4>
            </v-col>
            <v-col
                cols="9"
                class="d-flex justify-end"
            >
                <v-menu
                    v-model="menuShow"
                    location="left"
                    transition="scale-transition"
                    max-height="300px"
                    :close-on-content-click="false"
                    :close-on-back="false"
                >
                    <template v-slot:activator="{ props }">
                        <v-btn
                            append-icon="mdi-home-import-outline"
                            variant="tonal"
                            style="margin: 5px 5px 5px 0"
                            width="20"
                            v-bind="props"
                            :disabled="!designStore.editCss"
                        >
                            导入
                        </v-btn>
                    </template>
                    <v-card
                        width="250"
                        style="overflow-y: hidden"
                    >
                        <v-list
                            style="background-color: #f0f8ff; max-width: 250px"
                            max-height="250"
                        >
                            <v-list-group
                                v-for="(
                                    menu_names, label, index
                                ) in menuStyleSheet"
                            >
                                <template v-slot:activator="{ props }">
                                    <v-list-item
                                        v-bind="props"
                                        prepend-icon="mdi-language-css3"
                                        :title="label"
                                    ></v-list-item>
                                </template>
                                <v-chip-group
                                    column
                                    v-if="menu_names.length !== 0"
                                >
                                    <div
                                        style="
                                            display: flex;
                                            align-items: center;
                                        "
                                        v-for="(title, i) in menu_names"
                                        :key="i"
                                    >
                                        <v-chip
                                            label
                                            size="x-large"
                                            style="
                                                margin-left: 50px;
                                                width: 200px;
                                            "
                                            variant="text"
                                            :value="title"
                                            @click="
                                                (e) => {
                                                    this.menuShow = false
                                                    setSelectImportStyle(title)
                                                    importStyle()
                                                    this.executeFunc = true
                                                }
                                            "
                                            ><v-icon
                                                icon="mdi-close-circle-outline"
                                                class="deleteIcon"
                                                :value="title"
                                                @click="
                                                    (e) => {
                                                        this.executeFunc = false
                                                        this.delDialog = true
                                                    }
                                                "
                                            ></v-icon
                                            >{{ title }}</v-chip
                                        >
                                    </div>
                                </v-chip-group>
                            </v-list-group>
                        </v-list>
                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn
                                variant="tonal"
                                @click="menuShow = false"
                            >
                                Cancel
                            </v-btn>
                        </v-card-actions>
                    </v-card>
                </v-menu>
                <v-menu transition="scale-transition">
                    <template v-slot:activator="{ props }">
                        <v-btn
                            append-icon="mdi-home-export-outline"
                            variant="tonal"
                            style="margin: 5px 5px 5px 0"
                            width="20"
                            v-bind="props"
                            :disabled="!designStore.editCss"
                        >
                            导出
                        </v-btn>
                    </template>

                    <v-list style="background-color: aliceblue">
                        <v-list-item-title
                            class="option"
                            @click="dialogExport = true"
                            >导出样式表</v-list-item-title
                        >
                        <v-list-item-title
                            class="option"
                            @click="htmlExport()"
                            >导出完整代码</v-list-item-title
                        >
                    </v-list>
                </v-menu>
            </v-col>
        </v-row>
        <h4 style="margin: 5px 0 5px 5px; text-transform: uppercase"></h4>
        <div style="margin: 5px 0 5px 0; display: flex">
            <v-text-field
                clearable
                hide-details="auto"
                density="compact"
                label="name"
                variant="solo-filled"
                :disabled="!designStore.editCss"
                :value="attr.name"
                @update:modelValue="
                    (value) => {
                        attr.name = value
                        designStore.rerender()
                    }
                "
            ></v-text-field>
            <v-text-field
                v-if="designStore.disDelete.includes(tag)"
                clearable
                hide-details="auto"
                density="compact"
                label="content"
                variant="solo-filled"
                :disabled="!designStore.editCss"
                :value="designStore.currentDomPointer.children[0]"
                @update:modelValue="
                    (value) => {
                        if (tag === 'input') {
                            attr.placeholder = value
                        }
                        designStore.currentDomPointer.children[0] = value
                        designStore.rerender()
                    }
                "
            ></v-text-field>
        </div>
        <div style="margin: 5px 0 5px 0; display: flex">
            <v-text-field
                clearable
                hide-details="auto"
                density="compact"
                label="width/%"
                variant="solo-filled"
                :disabled="!designStore.editCss"
                :value="attr.style.width.replace('%', '')"
                @update:modelValue="
                    (value) => {
                        attr.style.width = value + '%'
                        designStore.rerender()
                    }
                "
            ></v-text-field>
            <v-text-field
                clearable
                hide-details="auto"
                label="height/%"
                density="compact"
                variant="solo-filled"
                :disabled="!designStore.editCss"
                :value="attr.style.height.replace('%', '')"
                @update:modelValue="
                    (value) => {
                        attr.style.height = value + '%'
                        designStore.rerender()
                    }
                "
            ></v-text-field>
        </div>
        <v-expansion-panels style="margin-top: 10px">
            <TextArea
                :attrAttr="attr"
                :disabled="!designStore.editCss"
            ></TextArea>
            <LayoutArea
                :attrAttr="attr"
                :disabled="!designStore.editCss"
            ></LayoutArea>
        </v-expansion-panels>
    </div>
    <div
        v-else
        style="text-align: center"
    >
        <h2 style="margin-top: 10px">画板信息</h2>
        <v-divider
            thickness="2"
            color="info"
            style="margin: 10px 0 10px 0"
        ></v-divider>
        <div>
            <h4>默认宽度: 1400px</h4>
            <h4>默认高度: 750px</h4>
        </div>
        <v-divider
            :thickness="2"
            color="info"
            style="margin: 10px 0 30px 0"
        ></v-divider>
        <div>
            <h2>快开始构建属于自己的页面吧~~~</h2>
        </div>
    </div>
    <v-dialog
        v-model="dialogExport"
        transition="dialog-bottom-transition"
        persistent
        width="auto"
    >
        <v-card title="导出样式表">
            <v-icon
                @click="dialogExport = false"
                style="position: absolute; right: 0%; margin: 10px"
                >mdi-close</v-icon
            >
            <v-sheet
                width="500"
                class="mx-auto"
                style="padding: 50px"
            >
                <v-form ref="form">
                    <v-text-field
                        v-model="myStyleInfo.name"
                        label="Name"
                        :rules="nameRules"
                    ></v-text-field>

                    <v-text-field
                        v-model="myStyleInfo.intro"
                        label="Introduction"
                    ></v-text-field>

                    <v-btn
                        @click="exportStyleSheet"
                        block
                        class="mt-2"
                        >确认</v-btn
                    >
                </v-form>
            </v-sheet>
        </v-card>
    </v-dialog>
    <v-dialog
        v-model="dialogImport"
        transition="dialog-bottom-transition"
        persistent
        width="auto"
    >
        <v-card>
            <div style="display: flex; justify-content: space-between">
                <h1 style="margin: 10px 0 0 10px; justify-content: flex-start">
                    预览样式表
                </h1>
                <div style="margin: 15px 15px 0 0; justify-content: flex-end">
                    <v-tooltip location="top">
                        <template v-slot:activator="{ props }">
                            <v-btn
                                density="comfortable"
                                size="large"
                                v-bind="props"
                                style="margin-right: 5px"
                                @click="confirmImport"
                                >确认</v-btn
                            >
                        </template>
                        <div style="font-size: 20px; text-align: center">
                            点击确认后将覆盖原样式<br />请谨慎操作！
                        </div>
                    </v-tooltip>
                    <v-btn
                        density="comfortable"
                        size="large"
                        @click="dialogImport = false"
                        >返回</v-btn
                    >
                </div>
            </div>
            <div
                class="previewArea"
                id="previewArea"
            ></div>
        </v-card>
    </v-dialog>
    <v-dialog
        v-model="delDialog"
        persistent
        width="auto"
    >
        <v-card style="width: 300px">
            <v-icon
                @click="delDialog = false"
                style="position: absolute; right: 0%"
                >mdi-close</v-icon
            >
            <v-card-text style="padding-top: 15%">
                Confirm to delete this styleSheet ?</v-card-text
            ><v-card-actions>
                <div style="position: absolute; right: 0%">
                    <v-btn
                        @click="confirmDelFunction"
                        style="color: cadetblue"
                        >confirm</v-btn
                    >
                    <v-btn @click="delDialog = false">close</v-btn>
                </div>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>
<script>
import { useDesignStore, domTreeMap } from '../../../../stores/design'
import { useBoxStore } from '../../../../stores/box'
import TextArea from './components/ElementStyle/TextArea.vue'
import LayoutArea from './components/ElementStyle/LayoutArea.vue'
import { createApp, h, nextTick } from 'vue'
import { useManageStore } from '../../../../stores/manage.js'

export default {
    components: {
        TextArea,
        LayoutArea
    },
    data() {
        return {
            designStore: useDesignStore(),
            manageStore: useManageStore(),
            box: useBoxStore(),
            render_trigger: true,
            myStyleInfo: {
                name: '',
                intro: '',
                label: ''
            },
            nameRules: [],
            dialogExport: false,
            dialogImport: false,
            styleSheets: [],
            selectImportStyle: {},
            name: [],
            menuShow: false,
            admins: [
                ['Management', 'mdi-account-multiple-outline'],
                ['Settings', 'mdi-cog-outline']
            ],
            menuStyleSheet: {},
            delDialog: false,
            executeFunc: true,
            selectedStyleSheetName: ''
        }
    },
    methods: {
        exportStyleSheet() {
            // 向后发送请求，保存 this.attr.style
            var s_ = this.attr.style
            // 下载
            const blob = new Blob([JSON.stringify(s_, null, 4)], {
                type: 'text/css'
            })
            const a = document.createElement('a')
            a.href = URL.createObjectURL(blob)
            a.download = this.myStyleInfo.name + '.css'
            a.click()
            URL.revokeObjectURL(a.href)

            const style1 = window.getComputedStyle(
                document.getElementById(this.attr.id),
                null
            )
            s_.width_px = style1.width
            s_.height_px = style1.height
            s_.display = ''
            s_.position = ''
            this.myStyleInfo.label = this.tag
            this.designStore
                .exportStyleSheet({ ...this.myStyleInfo, styleCss: s_ })
                .then((data) => {
                    this.getAllStyleSheets()
                    this.dialogExport = false
                    this.box.alert(
                        'success',
                        'Export Information',
                        'Successfully Export!'
                    )
                })
        },
        setSelectImportStyle(value) {
            this.selectedStyleSheetName = value
            if (this.executeFunc) {
                for (var i = 0; i < this.styleSheets.length; i++) {
                    if (this.styleSheets[i]['name'] === value) {
                        this.selectImportStyle = this.styleSheets[i]['styleCSS']
                        break
                    }
                }
            }
        },
        importStyle() {
            if (this.executeFunc) {
                this.dialogImport = true
                const vnode = h(
                    this.tag,
                    {
                        style: {
                            ...this.selectImportStyle,
                            ...{
                                width: this.selectImportStyle.width_px,
                                height: this.selectImportStyle.height_px
                            }
                        }
                    },
                    [
                        typeof this.designStore.currentDomPointer
                            .children[0] === 'string'
                            ? h(
                                  'p',
                                  this.designStore.currentDomPointer.children[0]
                              )
                            : ''
                    ]
                )
                nextTick(() => {
                    const app = createApp({ render: () => vnode })
                    app.mount('#previewArea')
                })
            }
        },
        confirmImport() {
            this.attr.style = { ...this.selectImportStyle }
            this.dialogImport = false
            this.designStore.rerender()
        },
        getAllStyleSheets() {
            this.designStore.getAllStyleSheets().then((data) => {
                this.styleSheets = data.style
                // 分类
                for (var i = 0; i < this.designStore.labels.length; i++) {
                    this.menuStyleSheet[this.designStore.labels[i]] = []
                }
                Object.keys(this.styleSheets).forEach((index) => {
                    this.menuStyleSheet[this.styleSheets[index]['label']].push(
                        this.styleSheets[index]['name']
                    )
                })
                this.name = data.name
                this.nameRules = [
                    (value) => {
                        if (value?.length > 0 && !this.name.includes(value)) {
                            return true
                        } else if (this.name.includes(value)) {
                            return 'The name already exists, change it please!'
                        } else {
                            return 'Name cannot be empty!'
                        }
                    }
                ]
            })
        },
        htmlExport() {
            // 获取 html 代码
            const htmlAll = this.designStore.getHtmlAll()

            // 下载
            const blob = new Blob([htmlAll], { type: 'type/html' })
            const a = document.createElement('a')
            a.href = URL.createObjectURL(blob)
            a.download = 'canvas.html'
            a.click()
            URL.revokeObjectURL(a.href)

            // 保存到后端
            this.designStore.currentDomPointer.attr.class =
                this.designStore.currentDomPointer.attr.class.replace(
                    'highlighted',
                    ''
                )
            const copyDom = this.designStore.eraseDefault(domTreeMap['canvas'])
            this.designStore
                .exportPageCode({
                    project_id: this.designStore.project_id,
                    html: htmlAll,
                    js: '',
                    domTreeMap: copyDom,
                    count: this.designStore.count
                })
                .then((data) => {
                    this.box.alert(
                        'success',
                        'Export Information',
                        'Successfully Export!'
                    )
                })
        },
        confirmDelFunction() {
            this.designStore
                .deleteStyleSheet({
                    name: this.selectedStyleSheetName
                })
                .then((data) => {
                    this.getAllStyleSheets()
                    this.delDialog = false
                    this.box.alert(
                        'success',
                        'Delete Information',
                        'Successfully Delete!'
                    )
                })
        }
    },
    computed: {
        attr() {
            return this.designStore.currentDomPointer.attr
        },
        tag() {
            return this.designStore.currentDomPointer.tag
        },
        trigger() {
            return this.designStore.trigger.elStyle
        }
    },
    created() {
        this.getAllStyleSheets()
    },
    watch: {
        trigger() {
            this.render_trigger = !this.render_trigger
            this.$forceUpdate()
        }
    },
    created() {
        if (this.designStore.project_id === '-1') {
            this.manageStore.create('新项目', '...').then((data) => {
                this.designStore.project_id = data.project_id
            })
        }
    }
}
</script>

<style>
.input {
    width: 20px;
    font-size: 14px;
    border-bottom: 3px solid rgb(97, 187, 209);
    outline: none;
    transition: 0.5s;
}
.input:focus {
    border-bottom: 3px solid rgb(0, 0, 0);
    transition: 0.5s;
}
.colorTip {
    width: 10px;
    height: 10px;
    cursor: grab;
}
.select {
    font-size: 14px;
    margin-left: 30px;
    border-bottom: 3px solid rgb(97, 187, 209);
    text-align: center;
    outline: none;
    transition: 0.5s;
}
.select:focus {
    border-bottom: 3px solid rgb(0, 0, 0);
    transition: 0.5s;
}
.previewArea {
    margin: 20px;
    min-width: 500px;
    display: flex;
    justify-content: center;
}

.option {
    padding: 10px;
    text-align: center;
    transition: background-color 0.3s;
    cursor: pointer;
}

.option:hover {
    background-color: #e0e0e0;
}

.deleteIcon {
    margin: 5px 5px 0 0;
    transition: 0.5s;
}

.deleteIcon:hover {
    color: red;
    font-size: 32px;
    transition: 0.5s;
}

</style>
